/**
 * Created by Administrator on 2017/7/19.
 */ 
let util = require('../util/util.js'); 
let variable = require('../data/variable.js');
let weixinSDK = require('../util/weixinSDK.js');
let rpc = require('../util/rpc.js');

let wechat = module.exports;

wechat.share = function (req, res) {
    res.header('Access-Control-Allow-Origin', '*');
    let params = util.getRequestParam(req);   
    console.log("获取分享>>>>>>>>>");  
    console.log(params);  
    if (!params.uid) {
        res.send({'error': 103, 'msg':'获取分享参数不对'}).end();
        return false;
    }   
    let url = params.url;
    let uid = params.uid; 
    
    rpc.dc.send('getTicket', {'uid': uid }, function (data) {
        var ticket  =  data.ticket; 
        console.log(ticket);  
        if(ticket && ticket!=null && ticket!=undefined ){ 
            weixinSDK.share(url,ticket,function(result){ 
                res.send(result).end();
            })  
            return false;
        } else  {   
            weixinSDK.ticket(uid,url,function(result){ 
                if (result.code && result.code!=0) {  
                    res.send({'error': 103, 'msg':'获取分享信息失败> '+result.code+','+result.message}).end(); 
                    return false;
                }   
                res.send(result).end(); 
            }); 
        }  
    }); 

};

wechat.run = function (req, res) {
    res.header('Access-Control-Allow-Origin', '*'); 
    let params = util.getRequestParam(req);  
    if(params.nonce==undefined || params.nonce==""){
        res.end('signature fail'); 
        return;
    }   
    let TOKEN = "caihu2018" 
    var key= [TOKEN,params.timestamp,params.nonce].sort().join(''); 
    //将token （自己设置的） 、timestamp（时间戳）、nonce（随机数）三个参数进行字典排序
    var sha1=require('crypto').createHash('sha1');
    //将上面三个字符串拼接成一个字符串再进行sha1加密
    sha1.update(key);
    var checkSignature = (sha1.digest('hex') == params.signature); 
    if(!checkSignature){
        //如果签名不对，结束请求并返回
        res.end('signature fail'); 
    }else{ 
        //如果请求是GET，返回echostr用于通过服务器有效校验
        res.end(params.echostr);
    }   
};

wechat.login = function (req, res) {  
    res.header('Access-Control-Allow-Origin', '*');
    var appid = variable.weixin[variable.weixin.use].appId;
    let params = util.getRequestParam(req);   
    var params_str = util.paramToUrl(params);
    var backUrl = "http://game.ku988.cn/wechat/callback?"+params_str;
    var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&response_type=code&scope=snsapi_userinfo&state=STATE&redirect_uri=${backUrl}#wechat_redirect`;
    console.log(url); 
    res.redirect(url); 
    res.end(); 
};  

wechat.callback = function (req, res) { 
    console.log("wechat callback");
    res.header('Access-Control-Allow-Origin', '*');  
    let params = util.getRequestParam(req);  
    let code = params.code; 
    if(code==null || code==""){ 
        res.redirect("http://game.ku988.cn:81/web/index.html");
        return;
    }   
    var params_str = util.paramToUrl(params);

    // var url = `http://game.ku988.cn:81/web/index.html?code=${code}&platform=weixin&proxy=weixin`;
    var url = "http://game.ku988.cn:81/web/index.html?platform=weixin&proxy=weixin&"+params_str;
    console.log(url);
    res.redirect(url);
    res.end();
};
